<template>
    <div class="sql-collection">
        <div class="sql-collection-content">
            <div class="sql-collection-content--title">SQL代码</div>
            <div>
                <div class="sql-collection-content--textarea">
                    <el-input
                        type="textarea"
                        :rows="3"
                        placeholder="请输入SQL语句"
                        v-model="textarea"
                        :disabled="isLock"
                        >
                    </el-input>
                </div>
                <div class="sql-collection-content--fields">
                    <div class="field" v-for="(field, i) in fields" :key="i">{{ field }}</div>
                </div>
            </div>
        </div>
        <div class="sql-collection-toolbar">
            <el-button class="sql-collection-btn" type="default" size="mini" @click="handleSQLClear">清空</el-button>
            <el-button class="sql-collection-btn" type="default" size="mini" :disabled="isLock" @click="handleFormat">格式化</el-button>
            <el-button class="sql-collection-btn" type="primary" size="mini" :disabled="isLock" @click="handleSQLTest">测试</el-button>
            <el-button class="sql-collection-btn" :type="isValid ? 'success' : 'danger'" size="mini" :disabled="!isValid" @click="handleSQLSubmit">{{ isLock ? "编辑" : "提交"}}</el-button>
        </div>

        <template v-if="excuteSQL">
            <div class="sql-collection-information">
                <div class="sql-collection-information--title">SQL运行信息</div>
                <div class="sql-collection-information--result">
                    <div class="sql">
                        <!-- <el-input type="textarea" v-model="excuteSQL" :rows="3" readonly></el-input> -->
                        <pre>{{ excuteSQL  }}</pre>
                    </div>
                    <div class="status" :class="{ fail: excuteErrorMsg }">{{ excuteErrorMsg || excuteStatus }}</div>
                    <div class="duration">
                        <span>时间: </span>
                        {{ excuteTime }}
                    </div>
                </div>
            </div>
            <div class="sql-collection-fields" v-if="excuteStatus == 'OK'">
                <div class="sql-collection-fields--title">结果</div>
                <base-table :table-data="tableData" :max-table-height="200" custom-class="sql-collection-table" style="alc(100% - 600px);"></base-table>
            </div>
        </template>
    </div>
</template>

<script>
import BaseTable from "@/components/Table";
import { tryInvokeApi } from "@/api/dataService/pool"
import { format } from 'sql-formatter';

export default {
    name: 'ApplicationSqlCollection',
    components: {
        BaseTable
    },
    props: {
        form: {
            type: Object,
            default: () => {
                return {}
            }
        }
   },
    data() {
        return {
            textarea: '',
            isValid: false,
            isLock: false,
            tableData: {
                coloums: [
                    // { label: "", props: "name" },
                ],
                records: []
            },
            fields: [],
            result: {},
            excuteStatus: '',
            excuteTime: '',
            excuteSQL: '',
            excuteErrorMsg: ''
        }
    },
    computed: {
        mergerRuleForm() {
            return Object.assign({}, {}, this.form)
        },
    },
    watch: {
        mergerRuleForm: {
            handler: function(newValue, oldValue) {
                if (newValue.sqlStatement) {
                    if (oldValue && oldValue.sqlStatement) {
                        if (this.formatSQL(newValue.sqlStatement) != this.formatSQL(oldValue.sqlStatement)) {
                            this.textarea = newValue.sqlStatement
                        }
                    } else {
                        this.textarea = newValue.sqlStatement
                    }
                }
            },
            deep: true,
            immediate: true
        },
        textarea(newValue, oldValue) {
            if (this.formatSQL(newValue) != this.formatSQL(oldValue)) {
                this.resetForm()
            }
        },
        isLock(value) {
            let params = {
                valid: value
            }
            if (value) {
                params.sqlStatement = this.textarea
                params.tableFieldId = []//[{'id':'8425','fieldName':'species_number'},{'id':'8426','fieldName':'drug_name'},{'id':8427,'fieldName':'notice_number'}]
                params.tableId = []//[{'tableName':'ods_nmpa_tcm_protect_drug_p_m_t','id':'491'}]
            }
            this.$emit('success', params)
        }
    },
    methods: {
        resetForm() {
            this.isValid = false
            this.isLock = false
        },
        formatSQL(sql) {
            return format(sql, {
                uppercase: true,
                linesBetweenQueries: 2,
            })
        },
        handleSQLClear() {
            this.textarea = ''
            this.isValid = false
            this.isLock = false

            this.tableData.coloums = []
            this.tableData.records = []
            this.fields = []
            this.result = {}

            this.excuteSQL = ''
            this.excuteErrorMsg = ''
        },
        handleFormat() {
            this.textarea = this.formatSQL(this.textarea)
        },
        handleSQLTest() {
            if (!this.textarea) return this.msgError('SQL 不能为空')
            let isValid = this.textarea.indexOf('insert') != -1 || this.textarea.indexOf('update') != -1 || this.textarea.indexOf('delete') != -1
            if (isValid) {
                this.$message.error('禁止插入、删除、更新语句')
                return
            }

            this.tableData.coloums = []
            this.tableData.records = []
            this.fields = []
            
            let params = {
                sql: this.textarea
            }
            tryInvokeApi(params).then(res => {
                this.excuteTime = `${res.excuteTime / 1000}s`
                this.excuteStatus = res.code == 200 ? 'OK' : 'FAIL'
                this.excuteSQL = this.formatSQL(this.textarea)
                if (res.code == 200) {
                    let coloums = [], fields = []
                    let results = res.data
                    if (results.length) {
                        for (const key in results[0]) {
                            if (Object.hasOwnProperty.call(results[0], key)) {
                                const item = results[0][key];
                                coloums.push({ label: key, props: key })
                                fields.push(key)
                            }
                        }
                    }

                    this.fields = fields
                    this.tableData.coloums = coloums
                    this.tableData.records = results
                    this.isValid = true   
                    this.excuteErrorMsg = ''
                } else {
                    this.excuteErrorMsg = res.desc
                }
            }).catch(() => {})
            
        },
        handleSQLSubmit() {
            this.isLock = !this.isLock
        }
    }
}
</script>

<style lang="scss" scoped>
.sql-collection {
    margin: 0 10px;
    padding: 15px 10px;
    width: calc(100% - 560px);
    box-shadow: 0 1px 1px rgb(0 0 0 / 5%), 0 2px 6px 0 rgb(0 0 0 / 5%);
    box-sizing: border-box;

    & > div {
        width: 100%;
    }

    &-content  {
        
        & > div:last-child {
            height: 200px;
            display: flex;
            align-items: flex-start;
        }

        &--title {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 8px;
            line-height: 32px;
        }

        &--textarea {
            flex: 1;
            height: 100%;
            margin-right: 15px;

            .el-textarea {
                height: 100%;
            }

            ::v-deep textarea {
                height: 100%;
                resize: none;
            }
        }

        &--fields {
            width: 300px;
            height: 100%;
            overflow-x: hidden;
            flex-shrink: 0;

            .field {
                padding: 6px 8px;
                margin-bottom: 2px;
                width: 100%;
                background-color: #FCFCFC;
                font-size: 12px;
                text-overflow: ellipsis;
                white-space: nowrap;
                overflow: hidden;

                &:not(:first-child) {
                    margin-top: -1px;
                }
            }
        }
    }

    &-toolbar {
        margin: 8px 0;
    }

    &-information {
        padding: 10px 0;
        // height: 80px;
        font-size: 12px;

        &--title {
            font-size: 14px;
            margin-bottom: 8px;
            font-weight: bold;
        }

        &--result {
            & > div {
                margin-bottom: 4px;
            }

            .sql {
                max-height: 90px;
                font-size: 16px;
                margin-bottom: 8px;

                pre {
                    font-size: 12px;
                    height: 100%;
                }

                .el-textarea {
                    height: 100%;
                }

                ::v-deep textarea {
                    height: 100%;
                    resize: none;
                }
            }

            .status {
                font-weight: bold;

                &.success {
                    color: #67C23A;
                }

                &.fail {
                    color: #F56C6C;
                }
            }

            .duration {
                & > span {
                    font-weight: bold;
                }
            }
        }
    }

    &-fields {
        &--title {
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 8px;
        }
    }
}
</style>

<style lang="scss">
.sql-collection-table {
    padding: 0;
}
</style>